<template>
  <div>
    <el-dialog
      :lock-scroll="false"
      title="Split order"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="650px"
      @close="cancel"
    >
      <el-row v-if="orderData.order" :gutter="20">
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ orderData.order.orderNumber }}</span>
              <el-tag
                style="float: right;cursor:pointer;"
                type="primary"
                @click="addOrder"
              >Add orders</el-tag>
            </div>
            <div
              v-for="(product, index) in orderData.orderDetails"
              :key="index"
            >
              <el-card
                v-if="product.quantity!==0"
                class="productItem"
                :body-style="{ padding: '0px' }"
              >
                <el-row>
                  <el-col class="productImgArea" :span="17">
                    <img
                      :src="
                        product.thumbnailUri.indexOf('http') === 0
                          ? product.thumbnailUri
                          : imgPrefix + product.thumbnailUri + imgSuffix
                      "
                      style="max-width: 60px"
                    >
                    &nbsp;<el-input-number v-model="product.quantity" size="mini" :min="1" :max="product.quantity" style="88px" />
                  </el-col>
                  <el-col class="addBtnArea" :span="7">
                    <el-dropdown
                      style="padding: 10px 0px 0px 0px;"
                      type="text"
                    >
                      <el-button
                        type="text"
                      >to<i
                        class="el-icon-arrow-down el-icon--right"
                      /></el-button>
                      <el-dropdown-menu v-if="sub > 0" slot="dropdown">
                        <el-dropdown-item v-for="(t, i) of sub" :key="i">
                          <el-button
                            type="text"
                            @click="orderBindProduct(i, index, product)"
                          >{{
                            orderData.order.orderNumber + "-" + (i + 1)
                          }}</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                      <el-dropdown-menu v-else slot="dropdown">
                        <el-dropdown-item>
                          <el-button
                            type="text"
                            @click="addOrder"
                          >Add orders</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card v-for="(t, i) of sub" :key="i" class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ orderData.order.orderNumber + "-" + (i + 1) }}</span>
              <el-tag
                style="float: right;cursor:pointer;"
                type="danger"
                @click="clearProduct(i)"
              >Delete</el-tag>
            </div>
            <div v-if="rightData[i]">
              <div
                v-for="(p, j) in rightData[i]"
                :key="j"
              >
                <el-card
                  class="productItem"
                  :body-style="{ padding: '0px' }"
                >
                  <el-row>
                    <el-col class="productImgArea" :span="24">
                      <img
                        :src="
                          p.thumbnailUri.indexOf('http') === 0
                            ? p.thumbnailUri
                            : imgPrefix + p.thumbnailUri + imgSuffix
                        "
                        style="max-width: 60px"
                      >
                      <span style="margin-left: 20px">Numbers：{{ p.quantity }}</span>
                    </el-col>
                  </el-row>
                </el-card>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row slot="footer">
        <el-button type="primary" @click="submitRes()">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    splitOrderData: {
      type: Object,
      required: true
    },
    splitOrder: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      cloneOrderData: JSON.parse(JSON.stringify(this.splitOrderData.data)),
      orderData: JSON.parse(JSON.stringify(this.splitOrderData.data)),
      sub: 1,
      rightData: [[]],
      dialogVisible: true
    };
  },
  methods: {
    orderBindProduct(subIndex, pIndex, productData) {
      const product = JSON.parse(JSON.stringify(productData));
      // 判断原分组是否只剩一个商品&一个数量
      if (this.orderData.orderDetails.filter(item => item.quantity > 0).length === 1) { // 只剩下一个商品时，判断移出数量
        const dangerNum = productData.quantity;
        let existedNum = 0;
        this.rightData.forEach(item => {
          if (item.length > 0) {
            item.forEach(it => {
              if (it.id === productData.id) {
                existedNum += it.quantity;
              }
            });
          }
        });
        if (this.cloneOrderData.orderDetails[pIndex].quantity - existedNum - dangerNum === 0) {
          return this.$message.warning('原订单中至少保留一件商品');
        }
      }

      var havedData = [];
      var havedLength = 0; // 拆分的总数量（计算后）
      // 判断所有分组，是否包含该商品
      this.rightData.forEach((item, index) => {
        if (item.length > 0) { // 分组有商品
          item.forEach((it, i) => {
            if (it.id === product.id) { // 包含
              if (subIndex === index) {
                it.quantity += product.quantity;
              }
              havedLength += it.quantity;
              const obj = {
                groupIndex: index,
                productIndex: i,
                quantity: it.quantity
              };
              havedData.push(obj);
            }
          });
        }
      });
      if (havedData.length === 0) { // 所有分组中都不存在
        this.rightData[subIndex].push(product);
        this.orderData.orderDetails[pIndex]['quantity'] = this.cloneOrderData.orderDetails[pIndex].quantity - product.quantity;
      } else { // 有分组已经存在
        // 判断将移至分组是否存在
        if (havedData.findIndex(item => item.groupIndex === subIndex) === -1) {
          // 将移至分组不存在该商品
          this.rightData[subIndex].push(product);
          this.orderData.orderDetails[pIndex]['quantity'] = this.cloneOrderData.orderDetails[pIndex].quantity - havedLength - product.quantity;
        } else {
          // 将移至分组存在商品
          this.orderData.orderDetails[pIndex]['quantity'] = this.cloneOrderData.orderDetails[pIndex].quantity - havedLength;
        }
      }
    },
    addOrder() {
      this.sub++;
      this.rightData.push([]);
    },
    clearProduct(index) {
      if (this.rightData.length > index) {
        const data = this.rightData[index];
        data.forEach(item => {
          const havaIndex = this.orderData.orderDetails.findIndex(it => item.id === it.id);
          this.orderData.orderDetails[havaIndex].quantity += item.quantity;
        });
        this.rightData.splice(index, 1);
      }
      this.sub--;
    },
    cancel() {
      this.splitOrderData.canSplit = false;
    },
    submitRes() {
      const params = [];
      const formerOrder = this.orderData.orderDetails.filter(item => item.quantity > 0);
      const formeitem = [];
      formerOrder.forEach(item => {
        const obj = {};
        obj['id'] = item.id;
        obj['quantity'] = item.quantity;
        formeitem.push(obj);
      });
      params.push({ details: formeitem });

      this.rightData.filter(item => item.length > 0).forEach(item => {
        const parentObj = {};
        const arr = [];
        item.forEach(it => {
          const obj = {};
          obj['id'] = it.id;
          obj['quantity'] = it.quantity;
          arr.push(obj);
        });
        parentObj['details'] = arr;
        params.push(parentObj);
      });
      this.splitOrder(this.orderData.order.id, params);
    }
  }
};
</script>

<style lang="scss" scoped>
.productItem {
  margin-bottom: 10px;
  .productImgArea {
    display: flex;
    padding: 10px;
    align-items: center;
    img {
      display: block;
    }
    .el-input-number--mini {
      width: 86px;
    }
  }
  .addBtnArea {
    margin-top: 12px;
  }
}
</style>
